package com.cwn.wizbank.comm.utils;

import com.cwn.wizbank.comm.exception.ImageNameException;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件操作辅助类
 * Created by Kenry.Xian on 2017/4/6 0006.
 */
public class FileHelper {
    /**通过文件路径创建File实例并创建其所在路径的文件夹
     * @param filePath
     * @return
     */
    public static File createFileAndFolder(String filePath) {
        filePath = filePath.replaceAll("\\\\", "/");
        String folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
        File folderFile = new File(folderPath);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }
        return new File(filePath);
    }

    /**
     * 保存上传的文件到指定
     *
     * @param savePath 保存路径
     * @param bytes    文件内容
     * @return
     * @throws IOException
     */
    public static File saveFileForMultipartFile(String savePath, byte[] bytes) throws IOException {
        File scormFile = FileHelper.createFileAndFolder(savePath);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(scormFile));
        stream.write(bytes);
        stream.close();
        return scormFile;
    }

    /**
     * 保存多个上传的文件到指定文件夹
     * @param savePath 保存路径
     * @param files 文件数组
     * @return
     * @throws IOException
     * @throws ImageNameException
     */
    public static List<String> saveFileForMultipartFiles(String savePath, MultipartFile[] files) throws IOException, ImageNameException {
        //返回文件名list
        List<String> imgNameList = new ArrayList<String>();
        String newImageName = null;
        String filePath = null;

        //判断file数组不能为空并且长度大于0
        if(null != files && files.length > 0){
            //循环files保存文件
            for(MultipartFile file: files){
                //格式化图片名字
                newImageName = ImageNameUtil.getImageName(file.getOriginalFilename());
                //文件的保存完整路径
                filePath = savePath + File.separator + newImageName;
                //保存文件
                FileHelper.saveFileForMultipartFile(filePath, file.getBytes());
                //保存文件成功后将名字添加到集合
                imgNameList.add(newImageName);
            }
        }
        return imgNameList;
    }

    /**
     * 上传
     **/
    public static String isFileMultipartUpload(MultipartFile file, String savePath) throws IOException {
        String name = "";
        if (file != null) {
            String filename = File.separator + file.getOriginalFilename();
            String lastName = filename.substring(filename.lastIndexOf("."));
            String newname = System.currentTimeMillis() + lastName;//新文件名
            savePath += newname;
            FileHelper.saveFileForMultipartFile(savePath, file.getBytes());
        }
        return name;
    }

    /**
     * @param file
     * @return 返回修改后的文件名
     */
    public static String fixFileName(MultipartFile file) {
        String name = "";
        if (file != null) {
            String filename = File.separator + file.getOriginalFilename();
            String lastName = filename.substring(filename.lastIndexOf("."));
            name = System.currentTimeMillis() + lastName;//新文件名
        }
        return name;
    }

    /**
     * 查看请求中是否有文件 有的话返回文件
     *
     * @param request
     * @return
     */
    public static MultipartFile isHaveFile(HttpServletRequest request) {
        MultipartFile file = null;
        if (request instanceof MultipartHttpServletRequest) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            file = multiRequest.getFile("file");
        }
        return file;
    }


    /**
     * 递归删除文件下所有文件，大量文件时存在性能问题，请使用线程执行
     *
     * @param dir
     * @return
     */
    public static boolean deleteFolder(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list(); //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteFolder(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /***
     * 文件下载
     * @param path 文件绝对路径
     * @param request
     * @param response
     */

    public static void downloadFile(String path, HttpServletRequest request, HttpServletResponse response) {
        OutputStream os = null;
        try {
            File file = new File(path);
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            String fileName = null;
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {   //IE浏览器
                fileName = URLEncoder.encode(file.getName(), "UTF-8");
            } else {
                fileName = URLDecoder.decode(file.getName(), "UTF-8");//其他浏览器
            }
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileName.getBytes("utf-8"), "ISO8859-1")); // 指定下载的文件名
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
